package com.mx.zb.wxhub.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eboge.zb.common.util.DomUtil;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;

@Controller
public class WxTicketService {

	private final Logger log = LoggerFactory.getLogger(this.getClass()); 
	
	public static final String AppID = "wx53f74cdf62bb3fa4";
	public static final String AppSecret="34df697ce25d8896bd2d7e9282c5a19e";
	
	//公众号消息校验Token	开发者在代替公众号接收到消息时，用此Token来校验消息。
	private static final String token ="8EAD8bd095a8634282edd2eeb2290d1";
	//公众号消息加解密Key	在代替公众号收发消息过程中使用。必须是长度为43位的字符串，只能是字母和数字。
	private static final String encodingAesKey = "8EAD8bd095a8634282edd2eeb2290d118EAD8bd095a";
	
	public static String componentVerifyTicket = null;
	
	
	@RequestMapping(value="/wx/ticket", method=RequestMethod.POST)
	@ResponseBody
	public String ticket(@RequestBody String paramStr, String signature, String timestamp, 
			String nonce, String encrypt_type, String msg_signature) throws Exception{
		log.info(paramStr);
		String encrypt = DomUtil.get(paramStr, "Encrypt");
		String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
		String fromXML = String.format(format, encrypt);
		
		WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, AppID);
		String midMsg = pc.decryptMsg(msg_signature, timestamp, nonce, fromXML);
		componentVerifyTicket = DomUtil.get(midMsg, "ComponentVerifyTicket");		
		
		log.info("componentVerifyTicket:"+componentVerifyTicket);
		
		return "success";
	}
	
}
